<template>
  <div class="main-content">

    <!-- 搜索框、搜索按钮和重置按钮 -->

    <div class="search-section">
      <el-input v-if="type === 'TEXT'" placeholder="请输入评测名称" class="input" size="mini" v-model="name"></el-input>
      <el-input v-else placeholder="请输入课程名称" class="input" size="mini" v-model="name"></el-input>
      <el-button type="info" plain class="button" size="mini" @click="search">查询</el-button>
      <el-button type="warning" plain class="button" size="mini" @click="reset">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-section">
      <el-button type="primary" @click="showAllClasses">全部班级</el-button>
      <el-button type="success" @click="showMyClasses">我的班级</el-button>
      <el-button type="warning" @click="showMyPapers">我的测评</el-button>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content-section">
      <!-- 右侧展示区域 -->
      <div class="display-section">
        <!-- 右侧展示图片和名称 -->
        <el-row :gutter="20">
          <el-col :span="6" class="col" v-for="item in displayedItems" :key="item.id">
            <img :src="item.img" alt="" class="image" @click="handleClassClick(item)">
            <div class="overflowShow">{{ item.className }}</div>
          </el-col>
        </el-row>
        <!-- 没有数据时的提示 -->
        <div v-if="displayedItems.length === 0" class="empty-message">
          {{ emptyMessage }}
        </div>
      </div>

      <!-- 我的测评的操作区域 -->
      <div v-if="type === 'TEXT'&&assessmentPapers.length > 0">
        <el-divider>{{ typeLabel }}</el-divider>
        <!-- 使用 v-if 控制显示条件 -->
        <el-table v-if="assessmentPapers.length > 0" :data="assessmentPapers" style="width: 100%">
          <el-table-column prop="id" label="测评ID"></el-table-column>
          <el-table-column prop="examName" label="评测名称"></el-table-column>
          <el-table-column prop="examTime" label="评测时间"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button
                  type="primary"
                  v-if="!scope.row.completed"
                  @click="openSubmissionDialog(scope.row)"
              >去完成</el-button>
              <el-button
                  type="success"
                  v-else
                  :disabled="scope.row.score !== null"
                  @click="openReviewDialog(scope.row)"
              >已完成</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="分数">
            <template v-slot="scope">
              {{ scope.row.score !== null ? scope.row.score : '/' }}
            </template>
          </el-table-column>
        </el-table>
        <!-- 使用 v-else 控制没有测评时的提示显示 -->
        <div v-if="assessmentPapers.length === 0" class="empty-message">
          {{ emptyMessage }}
        </div>
      </div>
    </div>

    <!-- 加入班级提示弹窗 -->
    <el-dialog title="提示" :visible.sync="joinClassDialogVisible" width="30%">
      <span>是否加入到该班级？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="joinClassDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmJoinClass">确定</el-button>
      </span>
    </el-dialog>

    <!-- 提交文件弹窗 -->
    <el-dialog title="提交文件" :visible.sync="submissionDialogVisible" width="30%">
      <p>评测名称: {{ currentPaper.examName }}</p>
      <div v-html="currentPaper.examFile" class="paper-content"></div>
      <el-upload class="avatar-uploader" :action="$baseUrl + '/files/upload'" :headers="{ token: user.token }" list-type="picture" :on-success="handleSuccess">
        <el-button type="primary">点击上传</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFile(currentPaper)">保存</el-button>
      </span>
    </el-dialog>

    <!-- 查看已提交文件弹窗 -->
    <el-dialog title="查看提交文件" :visible.sync="reviewDialogVisible" width="30%">
      <p>评测名称: {{ currentPaper.examName }}</p>
      <div v-html="currentPaper.examFile" class="paper-content"></div>
      <el-upload
          action="#"
          list-type="text"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="submittedFiles"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :on-error="handleError"
      >
        <el-button size="small" type="primary">重新上传</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="resubmitFile">重新提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import user from "@/views/manager/User.vue";

export default {
  data() {
    return {
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      name: '', // 搜索框输入的课程名称
      displayedItems: [], // 用于显示的班级或测评数据
      assessmentPapers: [], // 测评试卷数据
      type: 'ALlCLASS', // 默认类型为视频课程
      joinClassDialogVisible: false, // 加入班级弹窗可见性
      submissionDialogVisible: false, // 提交文件弹窗可见性
      reviewDialogVisible: false, // 查看已提交文件弹窗可见性
      selectedClass: null, // 选择的班级
      currentPaper: {}, // 当前选择的测评试卷
      submittedFiles: [], // 已提交文件列表
      currentfile:[],
      studentId:0,
      myClasses: [] // 虚拟的我的班级数据
    };
  },
  mounted() {
    // 初始化页面数据
    this.loadAllClasses(); // 加载所有班级数据（虚拟）
  },
  methods: {
    /**
     * 从数据库加载所有班级数据
     * 虚拟实现，实际应该通过 API 请求获取数据
     */
    loadAllClasses() {
      console.log(this.user.id); // 确保在方法中正确引用 this.user
      // 模拟从数据库获取数据
      this.$request.get('classes/selectAll').then(res=>{
        this.displayedItems=res.data
      })
      this.type = 'ALLCLASS';
      this.getMyClasses();
      this.assessmentPapers=[]
    },
    /**
     * 显示全部班级
     * 调用 loadAllClasses 方法加载所有班级数据
     */
    showAllClasses() {
      this.loadAllClasses();

    },
    /**
     * 显示我的班级
     * 虚拟实现，实际应该通过 API 请求获取数据
     */
    getMyClasses(){
      this.$request.get('classes/selectByUserId/'+this.user.id).then(res=>{
        this.myClasses=res.data
      })
      this.type = 'MYCLASS';
    },
    showMyClasses() {
      this.displayedItems=this.myClasses;
      this.assessmentPapers=[]
    },
    /**
     * 显示我的测评
     * 虚拟实现，实际应该通过 API 请求获取数据
     */
    showMyPapers() {
      this.$request.get('exam/selectByUserId/'+this.user.id).then(res=>{
        this.displayedItems=[]
        this.assessmentPapers=res.data

      })

      this.type = 'TEXT';
    },
    /**
     * 处理班级点击事件
     * 如果不是我的班级，则显示加入班级提示弹窗；否则导航到详情页
     * @param {Object} item 点击的班级对象
     */
    handleClassClick(item) {
      if (!this.myClasses.some(classItem => classItem.id === item.id)) {
        this.joinClassDialogVisible = true;
        this.selectedClass = item;
      } else {
        this.$router.push({ name: 'TeachingClass', params: { classId: item.id } });
      }
    },
    /**
     * 确认加入班级
     *
     */
    confirmJoinClass() {
      console.log(this.selectedClass)
      this.$request.post('student/add',{

      userId:this.user.id,
      classId:this.selectedClass.id,

      }).then(res=>{
        if (res.code === '200') {
          this.$message.success('操作成功')

          this.joinClassDialogVisible = false;
          this.showAllClasses();
        } else {
          this.$message.error(res.msg)
        }
      })
      this.joinClassDialogVisible = false;
      this.showMyClasses();
    },
    /**
     * 打开提交文档的弹窗
     * @param {Object} paper 当前选择的测评试卷
     */
    openSubmissionDialog(paper) {
      this.currentPaper = paper;
      this.submissionDialogVisible = true;
    },
    /**
     * 打开查看已提交文件的弹窗
     * @param {Object} paper 当前选择的测评试卷
     */
    openReviewDialog(paper) {
      this.currentPaper = paper;
      this.submittedFiles = [
        // 假设之前已提交的文件
        {name: '已提交文件1.docx', url: '#'},
        {name: '已提交文件2.pdf', url: '#'},
      ];
      this.reviewDialogVisible = true;
    },
    /**
     * 提交文件
     * 虚拟实现，实际应该通过 API 请求提交文件
     */
    submitFile(currentPaper) {
      console.log(currentPaper)
      this.$request.get('student/studentIdBy',{
        params:{
          userId:this.user.id,
        classId: currentPaper.classId,
        }
      }).then(res=>{
        console.log(res.data)
        this.studentId=res.data
      }),
      this.$request.post('grade/add',{
        answerFile: this.currentfile,
        examId:currentPaper.id,
        studentId: this.studentId
      }).then(res=>{
        this.submissionDialogVisible = false;
        this.currentPaper.completed = true;
      })

      console.log('文件已提交');
    },
    /**
     * 重新提交文件
     * 虚拟实现，实际应该通过 API 请求重新提交文件
     */
    resubmitFile() {
      this.reviewDialogVisible = false;
      console.log('文件已重新提交');
    },
    /**
     * 查询方法（未实现）
     * 虚拟实现，实际应该通过 API 请求执行查询操作
     */
    search() {
      if (this.type === 'ALLCLASS') {
        // 在全部班级中查询
        this.displayedItems = this.filterItems(this.displayedItems, this.name);
      } else if (this.type === 'TEXT') {
        // 在我的测评中查询
        this.assessmentPapers = this.filterAssessments(this.assessmentPapers, this.name);
      } else if (this.type === 'MYCLASS') {
        // 在我的班级中查询
        this.displayedItems = this.filterItems(this.displayedItems, this.name);
      }
    },
    /**
     * 重置方法（未实现）
     * 虚拟实现，实际应该通过 API 请求执行重置操作
     */
    reset() {
      console.log('重置功能未实现');
    },
    // 在班级或测评中进行筛选
    filterItems(items, name) {
      return items.filter(item => item.name.includes(name));
    },
    filterAssessments(papers, name) {
      return papers.filter(paper => paper.title.includes(name));
    },
    // 文件上传相关方法（虚拟实现）
      handlePreview(file) {
      this.currentfile=file
      console.log('预览文件', file);
    },
    handleRemove(file, fileList) {
      console.log('移除文件', file, fileList);
    },
    beforeUpload(file) {
      console.log('上传前检查文件', file);
      return true;
    },
    handleSuccess(res) {
      this.currentfile=res.data
    },
    handleError(err, file, fileList) {
      console.log('文件上传失败', err, file, fileList);
    }
  },
  computed: {
    // 根据类型显示不同的标题和消息
    typeLabel() {
      return {
        CLASS: '视频课程',
        TEXT: '测评试卷',
      }[this.type];
    },
    emptyMessage() {
      return {
        CLASS: '抱歉，当前没有课程！',
        /*TEXT:'抱歉，当前没有评测试卷！'*/
      }[this.type];
    },
  },
};
</script>

<style scoped>
.search-section {
  text-align: left;
  margin-top: 20px;
  margin-left: 10px;
}

.input {
  width: 200px;
}

.button {
  margin-left: 10px;
}

.button-section {
  text-align: left;
  margin-top: 20px;
  margin-left: 10px;
}

.main-content-section {
  width: 60%;
  margin: 50px auto;
  min-height: 1500px;
  margin-left: 10px;
}

.display-section {
  margin-top: 20px;
  margin-left: 10px;
}

.col {
  margin-bottom: 35px;
}

.image {
  width: 100%;
  height: 150px;
  border-radius: 5px;
  cursor: pointer;
}

.overflowShow {
  color: #333333;
  margin-top: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

.empty-message {
  text-align: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.paper-content {
  margin: 20px 0;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #f9f9f9;
}
</style>
